package com.kodin.polyfit;

import org.apache.commons.math3.analysis.ParametricUnivariateFunction;

public class MyFunction implements ParametricUnivariateFunction {
    public double value(double x, double... parameters) {
        double a = parameters[0];
        double b = parameters[1];
        double c = parameters[2];
        double d = parameters[3];
        return d + ((a - d) / (1 + Math.pow(x / c, b)));
    }

    public double[] gradient(double x, double... parameters) {
        double a = parameters[0];
        double b = parameters[1];
        double c = parameters[2];
        double d = parameters[3];

        double[] gradients = new double[4];
        double den = 1 + Math.pow(x / c, b);

        gradients[0] = 1 / den; // 对 a 求导

        gradients[1] = -((a - d) * Math.pow(x / c, b) * Math.log(x / c)) / (den * den); // 对 b 求导

        gradients[2] = (b * Math.pow(x / c, b - 1) * (x / (c * c)) * (a - d)) / (den * den); // 对 c 求导

        gradients[3] = 1 - (1 / den); // 对 d 求导

        return gradients;

    }
}

